package com.chensheng.service;

import com.chensheng.converter.OrderMaster2OrderDTO;
import com.chensheng.dao.OrderMasterDAO;
import com.chensheng.dto.OrderDTO;
import com.chensheng.dto.ResultDTO;
import com.chensheng.enums.OrderStatusEnum;
import com.chensheng.enums.PayStatusEnum;
import com.chensheng.enums.ResultErrorEnum;
import com.chensheng.exception.SellException;
import com.chensheng.model.OrderDetail;
import com.chensheng.model.OrderMaster;
import com.chensheng.model.ProductInfo;
import com.chensheng.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 下午 16:52 2018/5/15 0015
 */
@Service
@Slf4j
public class OrderService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private PayService payService;

    @Autowired
    private WebSocket webSocket;

    /*
     * 返回：orderId
     * */
    @Transactional
    public String create(OrderDTO orderDTO){

        //创建orderMaster
        String orderId = KeyUtil.genUniqueKey();
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        for(OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            //创建OrderDetail
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            if(productInfo == null){
                log.error("【创建订单】Error:{}", ResultErrorEnum.PRODUCT_NOT_EXIST_ERROR);
                throw new SellException(ResultErrorEnum.PRODUCT_NOT_EXIST_ERROR);
            }

            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            orderDetail.setProductName(productInfo.getProductName());
            orderDetail.setProductPrice(productInfo.getProductPrice());
            orderDetail.setProductIcon(productInfo.getProductIcon());
            Date date = new Date();
            orderDetail.setCreateTime(date);
            orderDetail.setUpdateTime(date);

            //插入order_detail表
            orderDetailService.saveOne(orderDetail);

            //扣库存
            if(productInfo.getProductStock() < orderDetail.getProductQuantity()){
                log.error("【创建订单】Error:{}, productStock:{}, reduction:{}",
                        ResultErrorEnum.PRODUCT_STOCK_NOTAVAIL_ERROR, productInfo.getProductStock(), orderDetail.getProductQuantity());
                throw new SellException(ResultErrorEnum.PRODUCT_STOCK_NOTAVAIL_ERROR);
            }
            productInfoService.decreaseStock(orderDetail.getProductQuantity(), orderDetail.getProductId());

            orderAmount = orderDetail.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);
        }

        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.UNPAYED.getCode());
        Date date = new Date();
        orderMaster.setCreateTime(date);
        orderMaster.setUpdateTime(date);

        //插入order_master表
        orderMasterService.saveOne(orderMaster);

        // 发送websocket消息
        webSocket.sendMessage(orderMaster.getOrderId());
        log.info("create send message");

        return orderId;
    }

    /*
    * 默认orderMaster 各方面都是合法的，都是外层判断好了
    * */
    @Transactional
    public void cancel(OrderMaster orderMaster) {
        // 设置order_master status 为cancel
        orderMasterService.setOrderStatus(OrderStatusEnum.CANCELED.getCode(), orderMaster.getOrderId());

        // 返还库存
        List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orderMaster.getOrderId());
        if(CollectionUtils.isEmpty(orderDetailList)){
            log.error("【取消订单】Errors:{}", ResultErrorEnum.ORDER_DETAIL_NOT_EXIST_ERROR);
            throw new SellException(ResultErrorEnum.ORDER_DETAIL_NOT_EXIST_ERROR);
        }

        productInfoService.increaseStock(orderDetailList);

        // 如果已支付，需要退款
        if(orderMaster.getPayStatus().equals(PayStatusEnum.PAYED.getCode())){
            //退款
            payService.refund(orderMaster);
        }
    }

    @Transactional
    public void paid(OrderMaster orderMaster){

        log.info("【订单支付完成】paid方法");

        //判断订单状态
        if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【订单支付完成】订单状态不正确，orderId={}, orderStatus={}", orderMaster.getOrderId(), orderMaster.getOrderStatus());
            throw new SellException(ResultErrorEnum.ORDER_STATUS_ERROR);
        }

        //判断订单状态
        if(!orderMaster.getPayStatus().equals(PayStatusEnum.UNPAYED.getCode())){
            log.error("【订单支付完成】订单支付状态不正确，orderDTO={}", orderMaster);
            throw new SellException(ResultErrorEnum.ORDER_PAY_STATUS_ERROR);
        }
        orderMasterService.setPayStatus(PayStatusEnum.PAYED.getCode(), orderMaster.getOrderId());
    }

    public List<OrderDTO> findList(Integer start, Integer offset){
        List<OrderMaster> orderMasterList = orderMasterService.findAll(start, offset);

        List<OrderDTO> orderDTOList = orderMasterList.stream()
                .map(e -> OrderMaster2OrderDTO.convert(e)).collect(Collectors.toList());

        return orderDTOList;
    }

    /*
    * 查询order_master里面有多少条记录
    * */
    public Integer count(){
        Integer count = orderMasterService.countAll();
        return count;
    }

    public OrderDTO findOne(String orderId){
        OrderMaster orderMaster = orderMasterService.findOneByOrderId(orderId);
        if(orderMaster == null){
            //log.error("【查询订单】Error:{}", ResultErrorEnum.ORDER_NOT_EXIST_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.ORDER_NOT_EXIST_ERROR);
        }
        List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orderId);
        if(CollectionUtils.isEmpty(orderDetailList)){
            throw new SellException(ResultErrorEnum.ORDER_DETAIL_NOT_EXIST_ERROR);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }


    @Transactional
    public void finish(OrderMaster orderMaster) {
        // 设置order_master status 为cancel
        if(!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【完结订单】订单状态不正确， orderId={}, orderStatus={}", orderMaster.getOrderId(), orderMaster.getOrderStatus());
            throw new SellException(ResultErrorEnum.ORDER_STATUS_ERROR);
        }
        orderMasterService.setOrderStatus(OrderStatusEnum.FINISHED.getCode(), orderMaster.getOrderId());

        //模板推送消息
    }
}
